import ccclass = cc._decorator.ccclass;
import {apiUtils} from "../web/api/ApiUtils";
import ItemFrame from "../item/itemFrame";
import property = cc._decorator.property;

@ccclass
export default class AchievementItem extends cc.Component {
  private isInit = false
  @property(ItemFrame)
  private itemFrame: ItemFrame = null;
  @property(cc.Label)
  private labelDes: cc.Label = null;
  @property(cc.Label)
  private labelProgress: cc.Label = null;
  @property(cc.Node)
  private btnGet: cc.Node = null;
  @property(cc.Node)
  private btnProgress: cc.Node = null;
  @property(cc.Node)
  private bg: cc.Node = null
  @property(cc.Node)
  private btnGetted: cc.Node = null

  private isLoaded = false;

  onLoad() {
    this.isLoaded = true
    this.init()
  }

  init() {
    if (!this.isLoaded || this.isInit) {
      return
    }
    this.isInit = true;
    this.labelDes.string = this.data.taskdescribe
    this.bg.active = this.index % 2 === 1
    this.itemFrame.setRewardId(this.data.reward)
    if (this.data.isGet) {
      // this.labelProgress.string = '已领取';
      this.btnGetted.active = true;
      this.btnGet.active = false
      this.btnProgress.active = false;
    } else {
      if (this.data.current >= this.data.target) {
        this.btnGet.active = true;
        this.btnProgress.active = false;
        this.btnGetted.active = false;
      } else {
        this.btnGetted.active = false;
        this.btnGet.active = false
        this.btnProgress.active = true;
      }
      this.labelProgress.string = `${this.data.current}/${this.data.target}`
    }
  }

  private data: { target?: number, current?: number, isGet?: boolean, reward?: number, id?: number, tasktype?: number, taskdescribe?: string } = {isGet: true}

  private index: number = 0;

  setInitData(option: any, index: number) {
    this.index = index;
    this.data = {...option}
    this.init();
  }

  async onGetTouch() {
    const res = await apiUtils.reqAchievementReward(this.data.id)
    if (res.code === 0) {
      this.data.isGet = false;
      this.btnGet.active = false
      this.btnProgress.active = true;
      this.labelProgress.string = '已领取';
      this.node.emit('on-get')
    }
  }
}